<template>
	<view class="container">
		<!-- 给用户添加文件权限信息 -->
		<view class="add-user-role" style="margin-bottom: 30px;">
			<uni-section title="给用户添加文件权限" type="line" padding>
				<uni-forms :model="userFileRoleData">
					<uni-forms-item label="fileId">
						<uni-easyinput v-model="userFileRoleData.fileId" placeholder="请输入文件ID"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="userIds">
						<uni-easyinput v-model="userFileRoleData.userIds" placeholder="请输入用户ID(多填以,隔开)"></uni-easyinput>
					</uni-forms-item>
				</uni-forms>
				<button class="button" type="primary" @click="addUserFileRole"><text class="button-text">添
						加</text></button>
			</uni-section>

		</view>
		<!-- 根据fileId查询用户权限文件信息 -->
		<view class="query-content">
			<h3 style="margin-bottom: 10px;">根据文件ID获取用户权限信息</h3>
			<view class="userFileRole-view">
				<view class="form-view" style="width: 50%;">
					<uni-forms ref="queryFormRef" :model="queryForm" :rules="rules" class="form-view">
						<view class="form-row">
							<!-- 文件列表 -->
							<uni-forms-item label="" name="fileId" class="form-item">
								<uni-easyinput v-model="queryForm.fileId" placeholder="请输入文件ID"
									trim="true"></uni-easyinput>
							</uni-forms-item>
						</view>
					</uni-forms>
				</view>
				<view class="query-btn" style="width: 50%;">
					<button type="primary" class="button" @click="queryUserRoleById">查 询</button>
				</view>
			</view>
		</view>


		<!-- 用户权限信息列表 -->
		<view class="uni-container">
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="handleSelectionChange">
				<uni-tr>
					<uni-th width="150" align="center">用户名</uni-th>
					<uni-th width="150" align="center">昵称</uni-th>
					<uni-th width="150" align="center">用户ID</uni-th>
					<uni-th width="150" align="center">联系方式</uni-th>
					<uni-th width="150" align="center">权限 ID</uni-th>
					<uni-th width="150" align="center">文件 ID</uni-th>
				
				</uni-tr>
				<uni-tr v-for="(item, index) in paginatedUserFileRoleList" :key="index" :data-file-id="item.roleId">
					<uni-td>{{ item.contacts.userName }}</uni-td>
					<uni-td>{{ item.contacts.nickName }}</uni-td>
					<uni-td>{{ item.userId }}</uni-td>
					<uni-td>{{ item.contacts.phonenumber }}</uni-td>
					<uni-td>{{ item.roleId }}</uni-td>
					<uni-td>{{ item.fileId }}</uni-td>
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box">
				<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
					@change="change" />
			</view>
			<!-- 新增批量删除按钮 -->
			<button type="warn" size="mini" @click="batchDelete">批量删除</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import config from '@/config/config.js';
	import roleApi from '@/api/role.js';
	import MD5 from 'js-md5';
	const {
		appId,
		appKey
	} = config;

	const userFileRoleData = ref({
		fileId: '',
		userIds: ''
	});


	const addUserFileRole = () => {
		const {
			fileId,
			userIds
		} = userFileRoleData.value;

		// 确保 fileId 和 userIds 是有效的
		if (!fileId || !userIds) {
			uni.showToast({
				title: '文件ID或用户ID不能为空',
				icon: 'none'
			});
			return;
		}
		const timestamp = new Date().getTime();
		const param = `ApiRequest{appId=${appId},appKey=${appKey},timeStamp=${timestamp}}`;
		const tokenStr = MD5(param);
		console.log("timestamp----->", timestamp)
		console.log("tokenStr----->", tokenStr)
		// 构建请求的 URL
		const pathUrl =
			`${config.apiBaseUrl}/file/api/addUserRole?appId=${appId}&timeStamp=${timestamp}&token=${tokenStr}`;
		const finalUrl = `${pathUrl}&fileId=${fileId}&userIds=${userIds}`;

		// 设置请求头
		const headers = {
			'Content-Type': 'application/json'
		};

		// 发起POST请求
		uni.request({
			url: finalUrl,
			method: 'POST',
			header: headers,
			data: {}, // 如果需要发送数据，可以在这里填写
			success: (res) => {
				console.log('请求成功', res);
				if (res.data.code === 200) {
					// 请求成功，处理响应数据
					uni.showToast({
						title: '文件权限添加成功',
						icon: 'success'
					});
				} else {
					// 请求成功，但服务器返回错误
					uni.showToast({
						title: '添加失败：' + (res.data.message || '未知错误'),
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error('请求失败', err);
				uni.showToast({
					title: '请求失败，请检查网络或联系管理员',
					icon: 'none'
				});
			}
		});
	};

	const queryForm = ref({
		userId: '', // 用户id 必填
		createBy: '', // 创建者
		classesId: '', // 班级ID，
		fileId: '',
	});
	const queryFormRef = ref(null);

	const userFileRoleList = ref([]); // 初始化用户权限信息列表
	const pageSize = ref(10);
	const pageCurrent = ref(1);
	const total = ref(0);
	const loading = ref(false);

	const paginatedUserFileRoleList = computed(() => {
		const start = (pageCurrent.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		return userFileRoleList.value.slice(start, end);
	});

	// 根据fileId查询用户权限信息
	const queryUserRoleById = () => {
		queryFormRef.value.validate().then(res => {
			console.log('表单验证通过', queryForm.value);
			// 如果有文件ID，则根据文件ID查询文件
			roleApi.getUserRoleByFileId(queryForm.value.fileId).then(apiRes => {
				if (apiRes.code === 200) {
					console.log('根据文件ID查询用户权限成功', apiRes);
					userFileRoleList.value = apiRes.data;
					total.value = userFileRoleList.value.length; // 设置总记录数
				}
			});
		}).catch(err => {
			console.error('表单验证失败', err);
		});
	};


	// 新增批量删除相关逻辑
	const selectedFileIds = ref([]);
	// 新增批量删除相关逻辑
	const handleSelectionChange = (e) => {
		const selectedIndexes = e.detail.index;
		console.log("selectedIndexes--->", selectedIndexes);
		// 拿到勾选数据的id放到selectedFileIds.value中
		selectedFileIds.value = selectedIndexes.map(index => userFileRoleList.value[index].roleId);
	};

	const batchDelete = () => {
		console.log("selectedFileIds.value---->", selectedFileIds.value)
		uni.showModal({
			title: '确认批量删除',
			content: '您确定要删除选中的用户文件权限吗？',
			success: function(res) {
				if (res.confirm) {
					roleApi.deleteUserFileRoleByFileIdList(selectedFileIds.value).then(apiRes => {
						if (apiRes.code === 200) {
							uni.showToast({
								title: '批量删除成功!',
								icon: 'success',
							});
							// 从userFileRoleList中移除被删除的权限
							selectedFileIds.value.forEach(roleId => {
								const index = userFileRoleList.value.findIndex(item => item
									.roleId === roleId);
								if (index !== -1) {
									userFileRoleList.value.splice(index, 1);
								}
							});
							// 根据情况调整pageCurrent
							if (pageCurrent.value === Math.ceil(userFileRoleList.value.length / pageSize
									.value) && pageCurrent.value > 1) {
								pageCurrent.value--;
							}
							total.value = userFileRoleList.value.length;
						} else {
							uni.showToast({
								title: '批量删除失败：' + (apiRes.message || '未知错误'),
								icon: 'none',
							});
						}
					})
				} else if (res.cancel) {
					// 用户点击了取消，不做任何操作
					console.log('用户点击取消');
				}
			}
		});
	};


	const rules = {
		fileId: {
			rules: [{
					required: true,
					errorMessage: '请输入fileId',
				},
				{
					minLength: 1,
					maxLength: 50,
					errorMessage: 'ID长度在 {minLength} 到 {maxLength} 个字符',
				}
			]
		},
	}
</script>

<style lang="scss">
	.container {
		padding: 30px;
	}

	.form-view {
		display: flex;
		flex-direction: column;
		align-items: stretch;
	}

	.form-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}

	.form-item {
		flex: 1;
		margin-right: 10px;

		&:last-child {
			margin-right: 0;
		}
	}

	button {
		margin: 0 10px;
	}

	.userFileRole-view {
		display: flex;
		justify-content: space-between;
	}

	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	@mixin height {
		/* #ifndef APP-NVUE */
		height: 100%;
		/* #endif */
		/* #ifdef APP-NVUE */
		flex: 1;
		/* #endif */
	}

	.box {
		@include flex;
	}

	.button {
		@include flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		height: 35px;
		margin: 0 5px;
		border-radius: 5px;
	}

	.example-body {
		background-color: #fff;
		padding: 10px 0;
	}

	.button-text {
		color: #fff;
		font-size: 12px;
	}

	.popup-content {
		@include flex;
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: 50px;
		background-color: #fff;
	}

	.popup-height {
		@include height;
		width: 200px;
	}

	.text {
		font-size: 12px;
		color: #333;
	}

	.popup-success {
		color: #fff;
		background-color: #e1f3d8;
	}

	.popup-warn {
		color: #fff;
		background-color: #faecd8;
	}

	.popup-error {
		color: #fff;
		background-color: #fde2e2;
	}

	.popup-info {
		color: #fff;
		background-color: #f2f6fc;
	}

	.success-text {
		color: #09bb07;
	}

	.warn-text {
		color: #e6a23c;
	}

	.error-text {
		color: #f56c6c;
	}

	.info-text {
		color: #909399;
	}

	.dialog,
	.share {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
	}

	.dialog-box {
		padding: 10px;
	}

	.dialog .button,
	.share .button {
		/* #ifndef APP-NVUE */
		width: 100%;
		/* #endif */
		margin: 0;
		margin-top: 10px;
		padding: 3px 0;
		flex: 1;
	}

	.dialog-text {
		font-size: 14px;
		color: #333;
	}
</style>